"use client";

import React, { useState, useMemo } from "react";

import {
    AllCommunityModule,
    themeQuartz,
    ClientSideRowModelModule,
    ModuleRegistry,
    ValidationModule,
} from "ag-grid-community";
import {
    ColumnMenuModule,
    ColumnsToolPanelModule,
    ContextMenuModule,
    FiltersToolPanelModule,
    LicenseManager,
    PivotModule,
    RowGroupingPanelModule,
} from "ag-grid-enterprise";
import ConfigPanel from "./ConfigPanel";
import DynGrid from "./DynGrid";
import { AG_GRID_LOCALE_CN } from '@ag-grid-community/locale';
// 导入配置管理工具
import { agGridConfig, validateConfig } from "../../utils/config";

// 注册必要模块
ModuleRegistry.registerModules([
    AllCommunityModule,
    ClientSideRowModelModule,
    ColumnsToolPanelModule,
    ColumnMenuModule,
    ContextMenuModule,
    PivotModule,
    FiltersToolPanelModule,
    RowGroupingPanelModule,
    ValidationModule /* 仅开发环境使用 */,
]);


// 验证配置并设置许可证密钥
validateConfig();
if (agGridConfig.licenseKey) {
    LicenseManager.setLicenseKey(agGridConfig.licenseKey);
} else {
    console.warn('ag-Grid 许可证密钥未配置，请检查环境变量 NEXT_PUBLIC_AG_GRID_LICENSE_KEY');
}

// 主题选项（可扩展）
const themeOptions = [
    { label: 'Quartz（深色）', value: 'ag-theme-quartz-dark' },
    { label: 'Alpine（浅色）', value: 'ag-theme-alpine' },
    { label: 'Balham', value: 'ag-theme-balham' },
];

// 默认列定义示例
const defaultColumnDefs = [
    
    {
        field: "country",
        rowGroup: true,                    // 按国家分组
        headerName: "国家"
    },
    {
        field: "sport",
        pivot: true,                       // 体育项目作为透视列
        headerName: "体育项目"
    },
    {
        field: "year",
        pivot: true,                       // 年份作为透视列
        headerName: "年份"
    },
    {
        field: "gold",
        aggFunc: "sum",                    // 金牌数量求和
        headerName: "金牌总数"
    }
];

// 默认数据源URL
const defaultDataUrl = "https://www.ag-grid.com/example-assets/olympic-winners.json";

export default function AgGridDynPage() {
    // 数据源URL
    const [dataUrl, setDataUrl] = useState(defaultDataUrl);
    // 列定义（JSON字符串）
    const [columnDefsStr, setColumnDefsStr] = useState(JSON.stringify(defaultColumnDefs, null, 2));
    // 主题
    const [theme, setTheme] = useState(themeOptions[0].value);
    // 表格数据
    const [rowData, setRowData] = useState([]);
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 列定义（对象）
    const columnDefs = useMemo(() => {
        try {
            return JSON.parse(columnDefsStr);
        } catch {
            return defaultColumnDefs;
        }
    }, [columnDefsStr]);

    // 拉取数据
    const fetchData = async () => {
        setLoading(true);
        try {
            const res = await fetch(dataUrl);
            const data = await res.json();
            setRowData(data);
        } catch (e) {
            setRowData([]);
        }
        setLoading(false);
    };

    // 页面加载时自动拉取一次
    React.useEffect(() => {
        fetchData();
        // eslint-disable-next-line
    }, [dataUrl]);

    // 容器样式
    const containerStyle = { display: 'flex', height: '100vh', width: '100vw' };

    return (
        <div style={containerStyle}>
            <ConfigPanel
                dataUrl={dataUrl}
                setDataUrl={setDataUrl}
                columnDefsStr={columnDefsStr}
                setColumnDefsStr={setColumnDefsStr}
                theme={theme}
                setTheme={setTheme}
                fetchData={fetchData}
                themeOptions={themeOptions}
                defaultColumnDefs={defaultColumnDefs}
            />
            <DynGrid
                rowData={rowData}
                columnDefs={columnDefs}
                loading={loading}
                theme={theme}
            />
        </div>
    );
} 